'use strict';

exports.money = (val) => {
  const lang = this.ctx.get('Accept-Language')
  if (lang.includes('zh-CN')) {
    return `￥ ${val}`
  }
  return `$ ${val}`
}

exports.genAppError = ({ctx}) => {
  return (error) => {
    ctx.app.logger.info(error)
    return error
  }
}

exports.catchPromiseError = (e) => {
  this.ctx.app.logger.info(error)
  return error
}

exports.abortOnError = ({ctx, error = {}, code = error.code || 0, message = error.message}) => {
  if (code) {
    ctx.body = { code, message }
    return true
  }
}

exports.rules = {
  OffsetValidationRule: {
    offset: {
      type: 'int',
      required: true,
      min: 0
    },
    size: {
      type: 'int',
      required: true,
      max: 1000
    }
  }
}

exports.mongoose = {
  tranformId (doc, ret) {
    ret.id = ret._id;
    delete ret._id;
    return ret
  },

  tranformTime (doc, ret) {
    if (typeof ret.$time_fields === 'string') {
      ret.$time_fields = [ret.$time_fields]
    }

    if (ret.$time_fields instanceof Array) {
      for (let fieldName of ret.$time_fields) {
        if (ret.hasOwnProperty(fieldName) && ret[fieldName] instanceof Date) {
          ret[fieldName] = parseInt(ret[fieldName].getTime() / 1000)
        }
      }
    }

    delete ret.$time_fields

    return ret
  },

  tranformUser (doc, ret) {
    delete ret.password
    return ret
  }
}

exports.rest = {
  resp ({ctx, error = {}, code = error.code || 0, message = error.message || '', data}) {
    let body = { code, message, data }
    ctx.body = body

    return body
  }
}

exports.auth = {
  async logined ({ctx, username = ctx.session.username}) {
    if (!username) return false

    // validate username first.
    let count = await ctx.app.model.user.doc.find({username}).count()

    if (count === 1) return true

    if (count === 0) return false

    // mail to administrator of website
    ctx.app.logger.info(`more than one username '${count}' in database`)
    return false
  },

  logout ({ctx}) {
    ctx.session.username = null
  }
}
